import redis, json
from plugins.common import settings

# RedisCache = redis.Redis(
#     host=settings.servers.redis.ip, 
#     port=settings.servers.redis.port, 
#     db=settings.servers.redis.db, 
#     password=settings.servers.redis.auth)

# def redis_health():


# #存数据
# def set_data(key, data, ex=None):
#   return RedisCache.set(key, data, ex)

# def get_data(key):
#     info = RedisCache.get(key)
#     return info

class RedisCache:
    #初始化
    def __init__(self) -> None:
        self.link = redis.Redis(
            host=settings.servers.redis.ip, 
            port=settings.servers.redis.port, 
            db=settings.servers.redis.db, 
            password=settings.servers.redis.auth)
    
    #健康函数
    def health(self) -> bool:
        try:
            info = self.link.info()
            if info:
                return 'yes'
            else:
                return 'no'
        except Exception as e:
            return f"请求发生异常：{e}"
    
    #设置缓存
    def set(self, key, data, ex=None) -> bool:
        return self.link.set(key, data, ex=ex)
    
    #获得缓存
    def get(self, key) -> str:
        info = self.link.get(key)
        return info
    
    #删除缓存
    def remove(self, key) -> None:
        self.link.delete(key)

    #保存json内容
    def set_json(self, key, obj, ex=None) -> bool:
        data = json.dumps(obj)
        return self.set(key, data, ex)
    
    #获得对象内容
    def get_json(self, key) -> object:
        data = self.get(key)
        if data == None:
            return None
        
        return json.loads(data)

cache = RedisCache()